package com.jhws.business.card.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.jhws.business.card.bo.TblCardDimBo;
import com.jhws.common.Page;

@Transactional
public class TblCardDimHibernateDAO implements
		ITblCardDimDAO {

	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public TblCardDimBo getById(String strId) {
		return (TblCardDimBo) sessionFactory.getCurrentSession().get("com.jhws.business.card.bo.TblCardDimBo",
				strId);
	}

	public Page findTblCardDim(int start, int num, String whereClause)
			throws Exception {
		try {
			StringBuffer buf = new StringBuffer();
			buf.append("from TblCardDimBo ");
			buf.append(whereClause);
			buf.append("order by card_no");
			  
			Query query = sessionFactory.getCurrentSession().createQuery(buf.toString());
			query.setFirstResult(start);
			query.setMaxResults(num);
			List list = query.list();

			Page page = new Page(start, num, list);
			String hql = "select count(*) from TblCardDimBo "+ (whereClause == null || "".equals(whereClause.trim()) ? "" : whereClause.trim());
			query = sessionFactory.getCurrentSession().createQuery(hql);
			page.setTotalNumber(((Number)query.uniqueResult()).intValue());
			return page;
		} catch (Exception e) {
			System.out.println("======================e:"+e.getMessage());
			return new Page();
		}
	}

	public TblCardDimBo save(TblCardDimBo bo) {
		sessionFactory.getCurrentSession().saveOrUpdate(bo);
		return bo;
	}

	public List findTblCardDimByWhere(String whereClause) throws Exception {
		try {
			StringBuffer buf = new StringBuffer("from TblCardDimBo ");
			if(whereClause != null || !"".equals(whereClause))
				buf.append( whereClause );
			Query query = sessionFactory.getCurrentSession().createQuery(buf.toString());
			List list = query.list();
			return list;
		} catch (Exception e) {
			return new ArrayList();
		}
	}

	public void deleteTblCardDim(String CardCode) {
		
		this.sessionFactory.getCurrentSession().delete(getById(CardCode));
//		this.getSession().createQuery("delete from TblCardDimBo where Card_code = ?")
//				.setString(0, TblCardId).executeUpdate();
	}



}	
